package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author 壮哥
 * @Date 2021/10/10/19:03
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    @Async("taskExecutor")//异步方法执行
    public void insert(UserSearchDTO dto) {
        //检查参数
        if (dto==null|| StringUtils.isBlank(dto.getSearchWords())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.info("ApUserSearchServiceImpl insert entryId is not null:{} ",dto.getEntryId());
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据实体id和关键词查询  历史记录
        ApUserSearch userSearch = mongoTemplate.findOne(
                Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                        .and("keyword").is(dto.getSearchWords())), ApUserSearch.class);
        //存在 则更新时间
        if (userSearch!=null){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        //不存在  则创建新的历史记录(10条)
        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                        .with(Sort.by(Sort.Direction.DESC, "createTime")),
                ApUserSearch.class);

        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(behaviorEntry.getId());
        apUserSearch.setKeyword(dto.getSearchWords());
        if (userSearchList.size()<10){
            mongoTemplate.save(apUserSearch);
            return;
        }
        //查询历史纪录
        ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);
        mongoTemplate.findAndReplace(
                Query.query(Criteria.where("id").is(lastUserSearch.getId())),apUserSearch
        );
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        //检查参数
        ApUser user = AppThreadLocalUtils.getUser();
        //查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.info("ApUserSearchServiceImpl insert entryId is not null: {]",dto.getEntryId());
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询数据列表 按照时间倒叙
        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")),
                ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }
}
